﻿using System;
using System.Windows.Forms;
using Microsoft.Win32;
using System.ServiceProcess;
using System.Diagnostics;
using System.Runtime.InteropServices;


namespace AleScheduler
{
    public partial class configAleSchedulr : Form
    {
        string[] DaysOfWeek = { "Monday" , "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
        ServiceController AleScheduler_ServiceController = new ServiceController();
        #region Property Declaration
        private string pathexep;
        public string pathexe
        {
            get { return pathexep; }
            set { pathexep = value; }
        }
        #endregion
        public configAleSchedulr()
        {
            InitializeComponent();
        }


        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectType();
        }

        private void btnChoice_Click(object sender, EventArgs e)
        {
            OpenFileDialog opfile = new OpenFileDialog();
            opfile.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
            opfile.Filter = "Executable Files (*.exe)|*.exe|PowerShell Scripts (*.ps1)|*.ps1|Batch Files (*.bat)|*.bat|CMD Files (*.cmd)|*.cmd|All files (*.*)|*.*";
            opfile.Title = "AleScheduler - Select File to Schedule";
            if(opfile.ShowDialog() == DialogResult.OK)
                this.txtFileToSchedule.Text = opfile.FileName;
        }

        private void selectType()
        {
            switch (this.cmbSheduleType.SelectedIndex)
            {
                case 0:
                    //Daily Scheduled
                    chkweek.Visible = false;
                    dateTimePickerDay.Visible = false;
                    grpEveryMinutes.Visible = false;
                    this.textBoxWatch.Visible = false;
                    grpTimeToRun.Visible = true;
                    grpTriggers.Enabled = true;
                    btnSave.Enabled = true;
                    lblDay.Visible = false;
                    grpTimeToRun.Location = new System.Drawing.Point(39, 51);
                    break;
                case 1:
                    //Weekly Scheduled
                    this.lblDay.Text = "Day";
                    this.chkweek.Items.Clear();
                    this.chkweek.Items.AddRange(DaysOfWeek);
                    chkweek.Visible = true;
                    dateTimePickerDay.Visible = false;
                    grpEveryMinutes.Visible = false;
                    this.textBoxWatch.Visible = false;
                    grpTimeToRun.Visible = true;
                    grpTriggers.Enabled = true;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    lblDay.Visible = true;
                    grpTimeToRun.Location = new System.Drawing.Point(39, 98);
                    break;
                case 2:
                    //Monthly Scheduled
                    chkweek.Visible = false;
                    dateTimePickerDay.Visible = true;
                    //dateTimePickerDay.MinDate = Convert.ToDateTime("01/01/2000 00.00.00"); //Vista/7 Incopatible
                    dateTimePickerDay.CustomFormat = "dd";
                    grpEveryMinutes.Visible = false;
                    grpTimeToRun.Visible = true;
                    grpTriggers.Enabled = true;
                    this.textBoxWatch.Visible = false;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    lblDay.Visible = true;
                    grpTimeToRun.Location = new System.Drawing.Point(39, 98);
                    break;
                case 3:
                    //Single Times Scheduled
                    chkweek.Visible = false;
                    dateTimePickerDay.Visible = true;
                    dateTimePickerDay.MinDate = DateTime.Now.Date;
                    dateTimePickerDay.CustomFormat = "dddd dd MMMM yyyy";
                    grpEveryMinutes.Visible = false;
                    grpTimeToRun.Visible = true;
                    grpTriggers.Enabled = true;
                    this.textBoxWatch.Visible = false;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    lblDay.Visible = true;
                    grpTimeToRun.Location = new System.Drawing.Point(39, 98);
                    break;
                case 4:
                    //Repeated Scheduled
                    chkweek.Visible = false;
                    dateTimePickerDay.Visible = false;
                    grpEveryMinutes.Visible = true;
                    grpTimeToRun.Visible = false;
                    grpTriggers.Enabled = true;
                    this.textBoxWatch.Visible = false;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    lblDay.Visible = false;
                    grpTimeToRun.Location = new System.Drawing.Point(39, 98);
                    break;
                case 5:
                    //User Session Change (Logon/Logoff)
                    chkweek.Visible = true;
                    //Type of Session
                    this.lblDay.Text = "On";
                    chkweek.Items.Clear();
                    chkweek.Items.Add("Session Logon"); chkweek.Items.Add("Session Logoff");
                    chkweek.Items.Add("Session Lock"); chkweek.Items.Add("Session Unlock");
                    chkweek.Items.Add("Remote Connect"); chkweek.Items.Add("Remote Disconnect");
                    dateTimePickerDay.Visible = false;
                    grpEveryMinutes.Visible = false;
                    grpTimeToRun.Visible = false;
                    this.textBoxWatch.Visible = false;
                    grpTriggers.Enabled = true;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    lblDay.Visible = true;
                    grpTimeToRun.Location = new System.Drawing.Point(39, 98);
                    break;
                case 6:
                    //FileSystem Watcher
                    chkweek.Visible = true;
                    //Type of Session
                    this.lblDay.Text = "On";
                    chkweek.Items.Clear();
                    chkweek.Items.Add("Changed Event"); chkweek.Items.Add("Created Event");
                    chkweek.Items.Add("Deleted Event"); chkweek.Items.Add("Renamed Event");
                    chkweek.Items.Add("All Event");
                    this.textBoxWatch.Visible = true;
                    dateTimePickerDay.Visible = false;
                    grpEveryMinutes.Visible = false;
                    grpTimeToRun.Visible = false;
                    grpTriggers.Enabled = true;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    lblDay.Visible = true;
                    grpTimeToRun.Location = new System.Drawing.Point(39, 98);
                    break;
                case 7:
                    //Process Watcher
                    chkweek.Visible = true;
                    //Type of Session
                    this.lblDay.Text = "On";
                    chkweek.Items.Clear();
                    chkweek.Items.Add("Process Start"); chkweek.Items.Add("Process Stop");
                    chkweek.Items.Add("All Event");
                    this.textBoxWatch.Visible = true;
                    dateTimePickerDay.Visible = false;
                    grpEveryMinutes.Visible = false;
                    grpTimeToRun.Visible = false;
                    grpTriggers.Enabled = true;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    lblDay.Visible = true;
                    grpTimeToRun.Location = new System.Drawing.Point(39, 98);
                    break;
                default: 
                    this.lblDay.Text = "Day";
                    chkweek.Visible = false;
                    dateTimePickerDay.Visible = false;
                    grpEveryMinutes.Visible = false;
                    this.textBoxWatch.Visible = false;
                    grpTimeToRun.Visible = false;
                    grpTriggers.Enabled = false;
                    btnSave.Enabled = false;
                    btnCancel.Enabled = false;
                    lblDay.Visible = false;
                    grpTimeToRun.Location = new System.Drawing.Point(39, 98);
                    break;
            }
        }

        private void esciToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void checkeMail_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkeMail.Checked)
            {
                try
                {
                    RegistryKey reg = Registry.LocalMachine.OpenSubKey("Software", true).OpenSubKey("AleScheduler", true).OpenSubKey("MailConfig", true);
                    string Toemail = reg.GetValue("ToMAil").ToString();
                    string Fromemail = reg.GetValue("FromMail").ToString();
                    string STMPT = reg.GetValue("SMTPServer").ToString();
                    string SMTPSerPort = reg.GetValue("SMTPServerPort").ToString();
                }
                catch
                {
                    //Show an InputBox for eMail address
                    frmMailConfig mail = new frmMailConfig();
                    mail.ShowDialog();
                    if (mail != null)
                    {
                        mail.Close();
                        mail.Dispose();
                    }
                }
            }
        }


        public void UpdateListBox()
        {
            /// Clear the list box first
            listView1.Clear();
            listView1.Columns.Add("Schedule Name");
            listView1.Columns[0].Width = 130;
            listView1.Columns.Add("File");
            listView1.Columns[1].Width = 250;
            listView1.Columns.Add("Time");
            listView1.Columns[2].Width = 40;
            listView1.Columns.Add("Type");
            listView1.Columns[3].Width = 85;
            listView1.Columns.Add("Day");
            listView1.Columns[4].Width = 87;
            listView1.Columns.Add("Code");
            listView1.Columns[5].Width = 0;

            frmMailConfig.checkappkey();
            RegistryKey reg = Registry.LocalMachine.OpenSubKey("Software", false).OpenSubKey("AleScheduler", false);
            if (reg == null)
            {
                MessageBox.Show("Error unable to create the registry key 'AleScheduler'\nThe service needs to be installed before this app will run","AleScheduler");
                return;
            }

            RegistryKey subKey;
            string[] scheduletype = { "Daily", "Weekly", "Monthly", "Single Times", "Reapeted", "Session Change" };
            string[] subKeys = reg.GetSubKeyNames();
            string strExeName;
            string schType;
            string strTime;
            string strDay = "";
            string strEvery;

            ListViewItem lvItem;

            foreach (string strName in subKeys)
            {
                subKey = reg.OpenSubKey(strName);
                if (subKey == null || subKey.Name.EndsWith("MailConfig"))
                    continue;

                /// get the value from the subkey
                strExeName = subKey.GetValue("FileToRun").ToString();
                schType = subKey.GetValue("ScheduleType").ToString();
                strTime = subKey.GetValue("Time").ToString();
                strDay = subKey.GetValue("Day",string.Empty).ToString();
                int itimeRange = (int)subKey.GetValue("Time_Range",0);
                int iEvery = (int)subKey.GetValue("Every_Time",0);
                Int16 schitype = Convert.ToInt16(schType);
                bool Disabled = Convert.ToBoolean(subKey.GetValue("Disabled",false).ToString());
                int Code = Convert.ToInt32(subKey.GetValue("Code").ToString());

                string timeRange = string.Empty;
                switch (itimeRange)
                {
                    case 0:
                        timeRange = "sec";
                        strEvery = Convert.ToString(iEvery);
                        break;
                    case 1:
                        timeRange = "min";
                        strEvery = Convert.ToString(iEvery / 60);
                        break;
                    case 2:
                        timeRange = "hou";
                        strEvery = Convert.ToString((iEvery / 60) / 60);
                            break;
                    default:
                            timeRange = "sec";
                            strEvery = Convert.ToString(iEvery);
                            break;
                }

                lvItem = listView1.Items.Add(strName);
                lvItem.SubItems.Add(strExeName);

                switch (schitype)
                {
                    case 8:
                        //Process Watcher Type
                        lvItem.SubItems.Add(String.Empty);
                        string TextToDisplay = "All Event";
                        int OnWatcherType = Convert.ToInt16(subKey.GetValue("WatcherType").ToString());
                        switch (OnWatcherType) {
                            case 1:
                                TextToDisplay = "Process Start";
                                break;
                            case 2:
                                TextToDisplay = "Process Stop";
                                break;
                            case 3:
                                TextToDisplay = "All Event";
                                break;
                            default:
                                TextToDisplay = "All Event";
                                break;
                        }
                        lvItem.SubItems.Add(TextToDisplay);
                        lvItem.SubItems.Add("All Day");
                        break;
                    case 7:
                        //FileSystemWatcher Type
                        lvItem.SubItems.Add(String.Empty);
                        TextToDisplay = "All Event";
                        OnWatcherType = Convert.ToInt16(subKey.GetValue("WatcherType").ToString());
                        switch (OnWatcherType)
                        {
                            case 1:
                                TextToDisplay = "Changed Event";
                                break;
                            case 2:
                                TextToDisplay = "Created Event";
                                break;
                            case 3:
                                TextToDisplay = "Deleted Event";
                                break;
                            case 4:
                                TextToDisplay = "Renamed Event";
                                break;
                            case 5:
                                TextToDisplay = "All Event";
                                break;
                            default:
                                TextToDisplay = "All Event";
                                break;
                        }
                        lvItem.SubItems.Add(TextToDisplay);
                        lvItem.SubItems.Add("All Day");
                        break;
                    case 6:
                        //Session Change Type
                        lvItem.SubItems.Add(String.Empty);
                        TextToDisplay = scheduletype[schitype - 1];
                        int OnSessionType = Convert.ToInt16(subKey.GetValue("OnSessionChange").ToString());
                        switch (OnSessionType)
                        {
                            case 1:
                                TextToDisplay = "Session Logon";
                                break;
                            case 2:
                                TextToDisplay = "Session Logoff";
                                break;
                            case 3:
                                TextToDisplay = "Session Lock";
                                break;
                            case 4:
                                TextToDisplay = "Session Unlock";
                                break;
                            case 5:
                                TextToDisplay = "Remote Connect";
                                break;
                            case 6:
                                TextToDisplay = "Remote Disconnect";
                                break;
                            default:
                                TextToDisplay = scheduletype[schitype - 1];
                                break;
                        }
                        lvItem.SubItems.Add(TextToDisplay);
                        lvItem.SubItems.Add("All Day");
                        break;
                    case 5:
                        lvItem.SubItems.Add(strEvery + " " + timeRange + " Loop");
                        lvItem.SubItems.Add(scheduletype[schitype - 1]);
                        lvItem.SubItems.Add("All Day");
                        break;
                    case 4:
                        lvItem.SubItems.Add(strTime);
                        lvItem.SubItems.Add(scheduletype[schitype - 1]);
                        lvItem.SubItems.Add("");
                        break;
                    case 3:
                        lvItem.SubItems.Add(strTime);
                        lvItem.SubItems.Add(scheduletype[schitype - 1]);
                        lvItem.SubItems.Add(strDay.Substring(0, 2) + " of Month");
                        break;
                    case 2:
                        lvItem.SubItems.Add(strTime);
                        lvItem.SubItems.Add(scheduletype[schitype - 1]);
                        lvItem.SubItems.Add(strDay);
                        break;
                    default:
                        lvItem.SubItems.Add(strTime);
                        lvItem.SubItems.Add(scheduletype[schitype - 1]);
                        lvItem.SubItems.Add("All Day");
                        break;
                }
                lvItem.SubItems.Add(Code.ToString()); //Import an Invisible Column 'Code'
                if (Disabled)
                    listView1.Items[listView1.Items.Count - 1].ForeColor = System.Drawing.Color.Red;
                else
                    listView1.Items[listView1.Items.Count - 1].ForeColor = System.Drawing.Color.Black;
            }

        }

        private void configAleSchedulr_Load(object sender, EventArgs e)
        {
            setCurrentTime();
            UpdateListBox();
            listboxsel();
            Service_Control();

        }

        private void setCurrentTime()
        {
            DateTime now = new DateTime();
            now = DateTime.Now;
            this.numericUpDown1.Text = now.Hour.ToString();
            this.numericUpDown2.Text = now.Minute.ToString();
            this.cmbTimeRange.SelectedIndex = 0;
        }

        private void Service_Control()
        {

            if (IsServiceInstalled("AleScheduler_Service"))
            {
                AleScheduler_ServiceController.ServiceName = "AleScheduler_Service";
                AleScheduler_ServiceController.DisplayName = "AleScheduler_Service";
                AleScheduler_ServiceController.MachineName = System.Environment.MachineName;
                if (AleScheduler_ServiceController.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                btnStartStop.Text = "&Stop";
                this.lblServiceController.Text = "Service Running";
                this.lblServiceController.ForeColor = System.Drawing.Color.Green;
                }
                else
                {
                    btnStartStop.Text = "&Start";
                    this.lblServiceController.Text = "Service Stopped";
                    this.lblServiceController.ForeColor = System.Drawing.Color.Red;
                }
            }
            else
            {
                btnStartStop.Text = "&Install";
                this.lblServiceController.ForeColor = System.Drawing.Color.Violet;
                this.lblServiceController.Text = "Service not Installed";
            }

        }


        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ListView.SelectedListViewItemCollection lvItemCol = listView1.SelectedItems;
            if (this.listView1.Items.Count > 0 && this.listView1.SelectedItems.Count > 0)
            {
                /// get the enumerator
                System.Collections.IEnumerator colEnum = lvItemCol.GetEnumerator();

                /// move to the first
                colEnum.MoveNext();

                /// get the list view item
                ListViewItem lvItem = (ListViewItem)colEnum.Current;

                /// now remove the registry key
                RegistryKey regKey = Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("AleScheduler", true);

                if (regKey == null)
                {
                    MessageBox.Show(this, "Unable to open the registry key", "AleScheduler");
                    return;
                }

                regKey.DeleteSubKeyTree(lvItem.Text);

                UpdateListBox();
                this.txtScheduleName.Text = string.Empty;
                this.txtFileToSchedule.Text = string.Empty;
                this.txtExeArguments.Text = string.Empty;
                this.cmbSheduleType.SelectedIndex = -1;
            }
            listboxsel();

            //Try to Reload Settings in the AleScheduler_Service
            if (IsServiceInstalled("AleScheduler_Service") && AleScheduler_ServiceController.Status == ServiceControllerStatus.Running)
                AleScheduler_ServiceController.ExecuteCommand(129);
		}

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmMailConfig.checkappkey();
            try
            {
                string nomeSch = this.listView1.SelectedItems[0].Text;
                RegistryKey reg = Registry.LocalMachine.OpenSubKey("Software", false).OpenSubKey("AleScheduler", false).OpenSubKey(nomeSch);
                this.txtScheduleName.Text = nomeSch;
                string strDay = reg.GetValue("Day", string.Empty).ToString();
                this.txtFileToSchedule.Text = reg.GetValue("FileToRun").ToString();
                this.cmbSheduleType.SelectedIndex = Convert.ToInt16(reg.GetValue("ScheduleType").ToString()) - 1;
                string strTime = reg.GetValue("Time").ToString();
                numericUpDown1.Value = Convert.ToDecimal(strTime.Substring(0, 2));
                numericUpDown2.Value = Convert.ToDecimal(strTime.Substring(strTime.Length - 2, 2));
                if (this.cmbSheduleType.SelectedIndex == 6 | this.cmbSheduleType.SelectedIndex == 7)
                {
                    this.chkweek.SelectedIndex = (int)reg.GetValue("WatcherType", 0) - 1;
                    this.textBoxWatch.Text = (string)reg.GetValue("WatchFileDir", string.Empty);
                }
                else if (this.cmbSheduleType.SelectedIndex == 5)
                    this.chkweek.SelectedIndex = (int)reg.GetValue("OnSessionChange", 0) - 1;
                else if (this.cmbSheduleType.SelectedIndex == 2 || this.cmbSheduleType.SelectedIndex == 3)
                {
                    System.Globalization.DateTimeFormatInfo dtfi = (System.Globalization.DateTimeFormatInfo)System.Globalization.DateTimeFormatInfo.CurrentInfo.Clone();
                    dtfi.ShortDatePattern = "dd/MM/yyyy";
                    this.dateTimePickerDay.MinDate = DateTime.Parse(reg.GetValue("Day").ToString(), dtfi);
                    this.dateTimePickerDay.Value = DateTime.Parse(reg.GetValue("Day").ToString(), dtfi);
                }
                else if (this.cmbSheduleType.SelectedIndex == 1)
                {
                    string day = reg.GetValue("Day").ToString();
                    switch (day)
                    {
                        case "Monday":
                            this.chkweek.SelectedIndex = 0;
                            break;
                        case "Tuesday":
                            this.chkweek.SelectedIndex = 1;
                            break;
                        case "Wednesday":
                            this.chkweek.SelectedIndex = 2;
                            break;
                        case "Thursday":
                            this.chkweek.SelectedIndex = 3;
                            break;
                        case "Friday":
                            this.chkweek.SelectedIndex = 4;
                            break;
                        case "Saturday":
                            this.chkweek.SelectedIndex = 5;
                            break;
                        case "Sunday":
                            this.chkweek.SelectedIndex = 6;
                            break;
                    }

                }
                int tRange = Convert.ToInt32(reg.GetValue("Time_Range").ToString());
                this.cmbTimeRange.SelectedIndex = tRange;
                int nTime = (int)reg.GetValue("Every_Time", 0);
                switch (tRange)
                {
                    //Seconds Time Range
                    case 0:
                        this.numericUpDown3.Value = nTime;
                        break;
                    //Minutes Time Range
                    case 1:
                        this.numericUpDown3.Value = nTime / 60;
                        break;
                    //Hours Time Range
                    case 2:
                        this.numericUpDown3.Value = (nTime / 60) / 60;
                        break;
                }
                this.maskedTextBoxForTimes.Text = reg.GetValue("NumberOfTimes", string.Empty).ToString();
                this.checkeMail.Checked = Convert.ToBoolean(reg.GetValue("SendMail").ToString());
                this.checkDisabled.Checked = Convert.ToBoolean(reg.GetValue("Disabled").ToString());
                this.txtExeArguments.Text = reg.GetValue("Arguments", string.Empty).ToString();
                this.pathexe = reg.GetValue("PathEXE", string.Empty).ToString();
                //retrieve Timeout and reverse conversion
                string timet = reg.GetValue("Timeout").ToString();
                uint timeOut = (timet != string.Empty) ? Convert.ToUInt32(timet) : 0;
                if ((timeOut > 3600000) && (timeOut % ((timeOut / 60) / 60) == 0))
                {
                    timeOut = (timeOut / 60) / 60;
                    timeOut = timeOut / 1000;
                    this.txtTimeOut.Text = Convert.ToString(timeOut) + "hou";
                }
                else if ((timeOut > 60000) && (timeOut % (timeOut / 60) == 0))
                {
                    timeOut = timeOut / 60;
                    timeOut = timeOut / 1000;
                    this.txtTimeOut.Text = Convert.ToString(timeOut) + "min";
                }
                else if (timeOut > 1000)
                {
                    timeOut = timeOut / 1000;
                    this.txtTimeOut.Text = Convert.ToString(timeOut);
                }
                else
                    this.txtTimeOut.Text = string.Empty;

                //Log Into Text File Options
                this.chkLogFile.Checked = Convert.ToBoolean(reg.GetValue("LogFiles", false).ToString());
                this.txtLogPath.Text = reg.GetValue("LogDirectory", "%LOGDIR%").ToString();

                //Force Interact with Desktop
                this.chkInteractDesktop.Checked = Convert.ToBoolean(reg.GetValue("ForceInteractWithDesktop", false).ToString());

                //Get Window Mode Option
                this.comboBoxMode.SelectedIndex = (int)reg.GetValue("WindowMode", 1) - 1;

            } catch (Exception ex) {
                MessageBox.Show("Error editing Schedulation !" + Environment.NewLine +
                ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            } finally {
                //Set the Cancel Button Enabled
                this.btnCancel.Enabled = true;
            }

        }

        private void listboxsel()
        {
            if (this.listView1.Items.Count > 0 && this.listView1.SelectedItems.Count > 0)
            {
                this.deleteToolStripMenuItem.Enabled = true;
                this.editToolStripMenuItem.Enabled = true;
            }
            else
            {
                this.deleteToolStripMenuItem.Enabled = false;
                this.editToolStripMenuItem.Enabled = false;
            }
        }

        private void listView1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            listboxsel();
        }

        private void txtFileToSchedule_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            InputBoxResult test = InputBox.Show("Insert path of Application to Launch!\nIf not equal to exe path : ",
                "AleScheduler", (this.pathexe == string.Empty) ? (this.txtFileToSchedule.Text != string.Empty) ? System.IO.Path.GetDirectoryName(this.txtFileToSchedule.Text) : string.Empty : this.pathexe);
            if (test.ReturnCode == DialogResult.OK)
                this.pathexe = test.Text;
        }

        private void infoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutAleScheduler ab = new AboutAleScheduler();
            ab.ShowDialog();
        }

        private void checkeMail_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //Create a Context Menu
                ContextMenu mnuContextMenu = new ContextMenu();
                this.ContextMenu = mnuContextMenu;
                MenuItem mnuItemSetting = new MenuItem();
                MenuItem mnuItemSetting2 = new MenuItem();
                mnuItemSetting.Text = "Change Mail &Settings";
                mnuItemSetting2.Text = "&Delete Mail Settings";
                mnuContextMenu.MenuItems.Add(mnuItemSetting);
                mnuContextMenu.MenuItems.Add(mnuItemSetting2);
                mnuItemSetting.Click += new EventHandler(mnuItemSetting_Click);
                mnuItemSetting2.Click += new EventHandler(mnuItemSetting2_Click);

            }
        }
        private void mnuItemSetting_Click(object sender, System.EventArgs e)
        {
            //Show an InputBox for eMail address
            frmMailConfig mail = new frmMailConfig();
            mail.ShowDialog();
            if (mail != null)
            {
                mail.Close();
                mail.Dispose();
            }
        }

        private void mnuItemSetting2_Click(object sender, System.EventArgs e)
        {
            try
            {
                RegistryKey regKey = Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("AleScheduler", true);
                regKey.DeleteSubKeyTree("MailConfig");
            }
            catch
            {
                MessageBox.Show(this, "Unable to Delete Mail Settings!", "AleScheduler - Mail Settings");
            }
        }
        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                this.editToolStripMenuItem.PerformClick();
            }
        }

        private void picCurrentTime_Click(object sender, EventArgs e)
        {
            setCurrentTime();
        }

        private void txtScheduleName_TextChanged(object sender, EventArgs e)
        {
            this.checkeMail.Enabled = (this.txtScheduleName.Text != String.Empty);
            this.txtTimeOut.Enabled = (this.txtScheduleName.Text != String.Empty);
            this.txtFileToSchedule.Enabled = (this.txtScheduleName.Text != String.Empty);
            this.btnChoice.Enabled = (this.txtScheduleName.Text != String.Empty);
            this.txtExeArguments.Enabled = (this.txtScheduleName.Text != String.Empty);
            this.cmbSheduleType.Enabled = (this.txtScheduleName.Text != String.Empty);
            this.checkDisabled.Enabled = (this.txtScheduleName.Text != String.Empty);
            this.grpOptions.Enabled = (this.txtScheduleName.Text != String.Empty);
        }

        private void btnSave_Click_1(object sender, EventArgs e)
        {
            //Save Settings in the regestry 
            try
            {

                if (this.txtScheduleName.Text.Trim() == string.Empty || this.txtFileToSchedule.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Insert Name of schedule and File to Schedule !", "AleScheduler", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                else if (this.txtScheduleName.Text.Trim() == "MailConfig")
                {
                    MessageBox.Show("Unable to Save Schedulations" + Environment.NewLine
                        + "Name of schedule reserved !" + Environment.NewLine
                        + "Change Schedulations name", "AleScheduler", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                //Check if File to Schedule Exist
                if ((!System.IO.File.Exists(this.txtFileToSchedule.Text.Trim())) && (!this.txtFileToSchedule.Text.Trim().Contains("*")) && (!this.txtFileToSchedule.Text.Trim().Contains("?")))
                {
                    if (MessageBox.Show(this, "File To Schedule Not Found !" + Environment.NewLine +
                        "Do You want to save anyway ?", "AleScheduler", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
                        return;
                }


                frmMailConfig.checkappkey();
                RegistryKey reg = Registry.LocalMachine.OpenSubKey("Software", true).OpenSubKey("AleScheduler", true);
                #region Set Schedulations Code
                int Code = 0;
                RegistryKey subKey;
                string[] subKeys = null;
                try
                { subKeys = reg.GetSubKeyNames(); }
                catch
                { Code = 1; }
                foreach (string strName in subKeys)
                {
                    subKey = reg.OpenSubKey(strName);
                    if ((subKey == null) || (strName == "MailConfig"))
                        continue;
                    int regCode = (int)subKey.GetValue("Code");
                    if (regCode > Code)
                        Code = regCode;
                }
                Code++;
                #endregion
                if (reg == null)
                {
                    MessageBox.Show("Error unable to create the registry key 'AleScheduler'", "AleScheduler");
                    return;
                }

                //Check if Schedule name already Exist
                string[] subKeys2 = null;

                try
                {
                    subKeys2 = reg.GetSubKeyNames();
                }
                catch
                {

                }
                foreach (string strName in subKeys2)
                {
                    if (strName == txtScheduleName.Text.Trim())
                    {
                        if (MessageBox.Show(this, "Do you want to override the Setting for " + strName + " Task ?",
                            "AleScheduler", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
                            return;
                    }
                }

                //Create a new Regestry Schedule name
                RegistryKey newKey = reg.CreateSubKey(txtScheduleName.Text.Trim());
                if (newKey == null)
                {
                    MessageBox.Show("Error unable to create the registry key " + txtScheduleName.Text, "AleScheduler");
                    return;
                }

                //Set Application Default Path
                if ((!string.IsNullOrEmpty(this.pathexe)) && this.pathexe != this.txtFileToSchedule.Text.Trim() && this.txtFileToSchedule.Text != string.Empty)
                    this.pathexe = System.IO.Path.GetDirectoryName(this.txtFileToSchedule.Text.Trim());
                //Write value of Key, before test the existance of value
                RegistryKey checkreg = Registry.LocalMachine.OpenSubKey("Software", true).OpenSubKey("AleScheduler", true).OpenSubKey(this.txtScheduleName.Text, true);

                if (Convert.ToInt32(checkreg.GetValue("Code", "0")) == 0)
                {
                    newKey.SetValue("Code", Code);
                }

                newKey.SetValue("FileToRun", (string)txtFileToSchedule.Text.Trim());
                newKey.SetValue("ScheduleType", Convert.ToInt16(cmbSheduleType.SelectedIndex + 1));
                string hour = this.numericUpDown1.Value.ToString();
                string minutes = this.numericUpDown2.Value.ToString();
                if (hour.Length <= 1 && hour.StartsWith("0"))
                {
                    hour = "00";
                }
                else if ((hour.Length == 1) && (!hour.StartsWith("0")))
                {
                    hour = "0" + hour;
                }
                if (minutes.Length <= 1 && minutes.StartsWith("0"))
                {
                    minutes = "00";
                }
                else if ((minutes.Length == 1) && (!minutes.StartsWith("0")))
                    minutes = "0" + minutes;
                newKey.SetValue("Time", hour + ":" + minutes);
                if (this.cmbSheduleType.SelectedIndex == 6 | this.cmbSheduleType.SelectedIndex == 7)
                {
                    //Set The FileSystemWatcher Settings or Process Watcher
                    newKey.SetValue("WatcherType", this.chkweek.SelectedIndex + 1);
                    newKey.SetValue("WatchFileDir", this.textBoxWatch.Text.Trim());
                }
                else if (this.cmbSheduleType.SelectedIndex == 5)
                {
                    //if (this.cmbSheduleType.SelectedIndex == 5) is a Session Change Schedulation !
                    newKey.SetValue("OnSessionChange", this.chkweek.SelectedIndex + 1);
                    newKey.SetValue("Day", "All Day");
                }
                else if (this.cmbSheduleType.SelectedIndex == 2 || this.cmbSheduleType.SelectedIndex == 3)
                {
                    newKey.SetValue("Day", this.dateTimePickerDay.Value.ToShortDateString());
                }
                else if (this.cmbSheduleType.SelectedIndex == 1)
                {
                    newKey.SetValue("Day", DaysOfWeek[this.chkweek.SelectedIndex]);
                }
                else
                {
                    newKey.SetValue("Day", "All Day");
                }

                newKey.SetValue("Time_Range", this.cmbTimeRange.SelectedIndex);
                switch (this.cmbTimeRange.SelectedIndex)
                {
                    //Every Seconds Schedulations
                    case 0:
                        newKey.SetValue("Every_Time", (int)this.numericUpDown3.Value);
                        break;
                    //Every Minutes Schedulations
                    case 1:
                        newKey.SetValue("Every_Time", ((int)this.numericUpDown3.Value * 60));
                        break;
                    //Every Hours Schedulations
                    case 2:
                        newKey.SetValue("Every_Time", (((int)this.numericUpDown3.Value * 60) * 60));
                        break;
                }

                newKey.SetValue("SendMail", this.checkeMail.Checked);
                newKey.SetValue("Disabled", this.checkDisabled.Checked);
                newKey.SetValue("PathEXE", this.pathexe ?? string.Empty);
                newKey.SetValue("Arguments", this.txtExeArguments.Text.Trim());

                //Write Timeout value in milliseconds
                string valTimeOut = this.txtTimeOut.Text.Trim();
                int TimeOut = 0;
                if (valTimeOut.EndsWith("hou"))
                {
                    TimeOut = Convert.ToInt32(valTimeOut.Remove(valTimeOut.Length - 3, 3));
                    TimeOut = (TimeOut * 60) * 60; //Convert in Seconds
                    TimeOut = TimeOut * 1000; //Convert to Milliseconds
                    newKey.SetValue("Timeout", TimeOut);
                }
                else if (valTimeOut.EndsWith("min"))
                {
                    TimeOut = Convert.ToInt32(valTimeOut.Remove(valTimeOut.Length - 3, 3));
                    TimeOut = TimeOut * 60; //Convert in Seconds
                    TimeOut = TimeOut * 1000; //Convert to Milliseconds
                    newKey.SetValue("Timeout", TimeOut);
                }
                else if (valTimeOut != string.Empty)
                {
                    TimeOut = Convert.ToInt32(valTimeOut);
                    TimeOut = TimeOut * 1000; //Convert to Milliseconds
                    newKey.SetValue("Timeout", TimeOut);
                }
                else
                    newKey.SetValue("Timeout", TimeOut);

                //Log Text Files Option 
                newKey.SetValue("LogFiles", this.chkLogFile.Checked);
                newKey.SetValue("LogDirectory", this.txtLogPath.Text);

                //Write Force Interact with Desktop
                newKey.SetValue("ForceInteractWithDesktop", this.chkInteractDesktop.Checked);

                //Set Maximum Number Of EveryTime Schedule if necessary
                //Try to Read NumberOfTimes Value
                int numof = (int)newKey.GetValue("NumberOfTimes", 0);
                int setTimes = (this.maskedTextBoxForTimes.Text != string.Empty) ? Convert.ToInt32(this.maskedTextBoxForTimes.Text) : 0;
                int passTimes = (int)newKey.GetValue("PassedTimes", 0);
                if (this.maskedTextBoxForTimes.Text != string.Empty && this.maskedTextBoxForTimes.Text != "0")
                    newKey.SetValue("NumberOfTimes", setTimes);
                else
                {
                    if (numof > 0)
                        newKey.DeleteValue("NumberOfTimes");
                }
                if (numof != setTimes && passTimes > 0)
                    newKey.DeleteValue("PassedTimes");

                //Save Window Moder Option
                newKey.SetValue("WindowMode", this.comboBoxMode.SelectedIndex + 1);

                //Update the listView
                UpdateListBox();
                this.txtScheduleName.Text = string.Empty;
                this.txtFileToSchedule.Text = string.Empty;
                this.txtExeArguments.Text = string.Empty;
                this.pathexe = string.Empty;
                this.cmbSheduleType.SelectedIndex = -1;
                this.comboBoxMode.SelectedIndex = - 1;
                this.checkeMail.Checked = false;
                this.txtTimeOut.Text = String.Empty;
                this.chkInteractDesktop.Checked = false;
                this.chkLogFile.Checked = false;
                this.checkDisabled.Checked = false;

                //Set name for the service controller
                AleScheduler_ServiceController.ServiceName = "AleScheduler_Service";
                AleScheduler_ServiceController.DisplayName = "AleScheduler_Service";
                AleScheduler_ServiceController.MachineName = System.Environment.MachineName;
                //Try to Reload Settings in the AleScheduler_Service
                if (IsServiceInstalled("AleScheduler_Service") && AleScheduler_ServiceController.Status == ServiceControllerStatus.Running)
                    AleScheduler_ServiceController.ExecuteCommand(129);

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Saving Task !" + Environment.NewLine +
                    ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            //Update the listView
            UpdateListBox();
            this.txtScheduleName.Text = string.Empty;
            this.txtFileToSchedule.Text = string.Empty;
            this.txtExeArguments.Text = string.Empty;
            this.pathexe = string.Empty;
            this.cmbSheduleType.SelectedIndex = -1;
            this.comboBoxMode.SelectedIndex = -1;
            this.checkeMail.Checked = false;
            this.txtTimeOut.Text = String.Empty;
            this.chkLogFile.Checked = false;
            this.txtLogPath.Text = string.Empty;
            this.chkInteractDesktop.Checked = false;
            this.checkDisabled.Checked = false;
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            // Check the status.
            if (btnStartStop.Text == "&Install")
            {
                try
                {
                    string defaultfile = System.IO.Directory.GetCurrentDirectory() + System.IO.Path.PathSeparator + "AleScheduler_service.exe";
                    if (System.IO.File.Exists(defaultfile))
                    {
                        ServiceInstaller.ServiceInstaller.InstallAndStart("AleScheduler_Service", "AleScheduler", defaultfile);

                    }
                    else
                    {
                        OpenFileDialog op = new OpenFileDialog();
                        op.CheckFileExists = true;
                        op.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
                        op.Title = "Select AleScheduler_service to Install";
                        op.Filter = "Executable Files (*.exe)|*.exe|DLL Files (*.dll)|*.dll";
                        if (op.ShowDialog() == DialogResult.OK)
                        {
                            ServiceInstaller.ServiceInstaller.InstallAndStart("AleScheduler_Service", "AleScheduler", op.FileName);
                        }
                    }
                    Service_Control();
                }
                catch (Exception aex)
                {
                    MessageBox.Show("Error installing Alescheduler Service !" + Environment.NewLine +
                        aex.Message, Application.ProductName);
                }
            }
            else if (btnStartStop.Text == "&Start")
            {
                try
                {
                    // Change the service status - Start Service
                    AleScheduler_ServiceController.Start();

                    // Set the button caption.
                    btnStartStop.Text = "&Stop";
                    this.lblServiceController.Text = "Service Running";
                    this.lblServiceController.ForeColor = System.Drawing.Color.Green;
                }
                catch(Exception aex)
                {
                    MessageBox.Show("Error starting Alescheduler Service !" + Environment.NewLine +
                        aex.Message, Application.ProductName);
                }
            }
            else
            {
                try
                {
                    //Stopping the Service
                    AleScheduler_ServiceController.Stop();
                    btnStartStop.Text = "&Start";
                    this.lblServiceController.Text = "Service Stopped";
                    this.lblServiceController.ForeColor = System.Drawing.Color.Red;
                }
                catch (Exception aex)
                {
                    MessageBox.Show("Error stopping Alescheduler Service !" + Environment.NewLine +
                        aex.Message, Application.ProductName);
                }
            }
        }
        public static bool IsServiceInstalled(string serviceName)
        {
            // get list of Windows services
            ServiceController[] services = ServiceController.GetServices();

            // try to find service name
            foreach (ServiceController service in services)
            {
                if (service.ServiceName == serviceName)
                    return true;
            }
            return false;
        }
        private ListViewColumnSorter lvwColumnSorter;
        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            lvwColumnSorter = new ListViewColumnSorter();
            this.listView1.ListViewItemSorter = lvwColumnSorter;
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.listView1.Sort();
        }


        private void btnExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog sv = new SaveFileDialog();
            sv.CheckFileExists = false;
            sv.DefaultExt = ".reg";
            sv.Title = "Save Schedulations as REG File";
            sv.Filter = "Reg Files (*.reg)|*.reg";
            if (sv.ShowDialog() == DialogResult.OK)
            {
                System.Diagnostics.Process process1;
                process1 = new System.Diagnostics.Process();
                process1.EnableRaisingEvents = false;
                string strCmdLine;
                strCmdLine = "/C " + "regedit /e " + sv.FileName + " HKEY_LOCAL_MACHINE\\SOFTWARE\\AleScheduler";
                System.Diagnostics.Process.Start("CMD.exe", strCmdLine);
                process1.Close();
                }
            }

        private void Run_Now(object sender, EventArgs e)
        {
            ListView.SelectedListViewItemCollection lvItemCol = listView1.SelectedItems;
                System.Collections.IEnumerator colEnum = lvItemCol.GetEnumerator();
                colEnum.MoveNext();
                ListViewItem lvItem = (ListViewItem)colEnum.Current;
                int RegCode = Convert.ToInt32(lvItem.SubItems[5].Text);

            RegistryKey key;
                RegistryKey softwareKey = Registry.LocalMachine.OpenSubKey("Software");

                key = softwareKey.OpenSubKey("AleScheduler");
            RegistryKey subKey;

            string[] subKeys = null;

                subKeys = key.GetSubKeyNames();

            //Cicle for examine every Schedulations item in the regestry
            foreach (string strName in subKeys)
            {
                subKey = key.OpenSubKey(strName);
                if ((subKey == null) || (strName == "MailConfig"))
                    continue;

                int Code = Convert.ToInt32(subKey.GetValue("Code").ToString());
                if (RegCode == Code)
                {
                    string strExeName = subKey.GetValue("FileToRun").ToString();
                    string schType = subKey.GetValue("ScheduleType").ToString();
                    string strTime = subKey.GetValue("Time").ToString();
                    string strDay = subKey.GetValue("Day").ToString();
                    string strEvery = subKey.GetValue("Every_Time",string.Empty).ToString();
                    Int16 schitype = Convert.ToInt16(schType);
                    bool SendMail = Convert.ToBoolean(subKey.GetValue("SendMail").ToString());
                    bool Disabled = Convert.ToBoolean(subKey.GetValue("Disabled").ToString());
                    bool forceDesktop = Convert.ToBoolean(subKey.GetValue("ForceInteractWithDesktop").ToString());
                    string pathexe = subKey.GetValue("PathEXE").ToString();
                    string argument = subKey.GetValue("Arguments").ToString();
                    uint timeOut = Convert.ToUInt32(subKey.GetValue("Timeout").ToString());
                    string LogDirectory = subKey.GetValue("LogDirectory","%LOGDIR%").ToString();

                    System.Threading.Thread t = new System.Threading.Thread(delegate()
                    { Start_Scheduletions_Process(forceDesktop, strName, strExeName, pathexe, argument, timeOut, LogDirectory); });
                    t.Start();
                }
            }
        }
        

        #region Start_Scheduletions_Process
        //Method for start Schedulation process immadiatly Log in Text Files AND Interact with Desktop
        private bool Start_Scheduletions_Process(bool forceInteractWithDesktop, string strName, string strExeName, string pathexe, string strArgument, uint timeOut, string LogPath)
        {
            string errormessage = string.Empty;
            const int ERROR_FILE_NOT_FOUND = 2;
            const int ERROR_ACCESS_DENIED = 5;
            if (forceInteractWithDesktop)
            {
                //Launch Process as a User API for Force Interact with Desktop
                //Useful for force program to Interact wiith Desktop in Windows Vista/7/Server 2008
                if (!string.IsNullOrEmpty(strArgument))
                    AleUtil.ProcessAsUser.Launch(strExeName + " " + strArgument);
                else
                    AleUtil.ProcessAsUser.Launch(strExeName);

                //Log Process Starting
                AleUtil.appLog.WriteTextLog("(Task : " + strName + ")Start Process : " + strExeName + " (process forced to Interact with Desktop)", LogPath, strName);
                return true;
            }
            else
            {
                Process process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                try
                {
                    process.StartInfo = startInfo;
                    startInfo.FileName = strExeName;
                    startInfo.WorkingDirectory = pathexe;
                    if (strArgument != null && strArgument != string.Empty)
                        startInfo.Arguments = strArgument;
                    startInfo.UseShellExecute = true;
                    if (process.Start() == true)
                    {
                        AleUtil.appLog.WriteTextLog("(Task : " + strName + ")Process Started Succesfully " + startInfo.FileName, LogPath, strName);
                    }

                    #region Wait for the process Time Out.
                    if (timeOut > 0)
                    {
                        process.WaitForExit(Convert.ToInt32(timeOut));
                        //Check to see if the process is still running.
                        if (process.HasExited == false)
                            //Process is still running.
                            //Test to see if the process is hung uprocess.
                            if (process.Responding)
                                //Process was responding; close the main window.
                                process.CloseMainWindow();
                            else
                                //Process was not responding; force the process to close.
                                process.Kill();
                    }
                    #endregion
                }
                catch (System.ComponentModel.Win32Exception e)
                {
                    if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
                    {
                        errormessage = "(Task : " + strName + ")" + e.Message + ". Check the path of Schedulations : " + strName + ".";
                        AleUtil.appLog.WriteTextLog(errormessage, LogPath, strName);
                        return false;
                    }
                    else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
                    {
                        errormessage = "(Task : " + strName + ")" + e.Message + ". You do not have permission to execute : " + strExeName + ".";
                        AleUtil.appLog.WriteTextLog(errormessage, LogPath, strName);
                        return false;
                    }
                    else
                    {
                        errormessage = "(Task : " + strName + ")" + e.Message +
                            ". Generic error for execute : " + strExeName + ".\nOther Useful Information : \n" +
                        "Error Code : " + e.ErrorCode.ToString() + "\n" +
                        "Stack Trace : \n" + e.StackTrace;
                        AleUtil.appLog.WriteTextLog(errormessage, LogPath, strName);
                        return false;
                    }
                }
                catch (Exception g)
                {
                    errormessage = "(Task : " + strName + ")Generic Schedulations Execution Failure :\n" +
                        "Schedulations Name : " + strName + "\n" +
                        "Error Information :\n" + g.Message;
                    AleUtil.appLog.WriteTextLog(errormessage, LogPath, strName);
                    return false;
                }
                return true;
            }
        }
        #endregion
        private void listView1_MouseUp(object sender, MouseEventArgs e)
        {
            if ((e.Button == MouseButtons.Right && listView1.Items.Count > 0) && (listView1.SelectedItems.Count > 0))
            {
                //Create a Context Menu
                ContextMenu mnuContextMenu = new ContextMenu();
                this.listView1.ContextMenu = mnuContextMenu;
                MenuItem mnuItemSetting = new MenuItem();
                mnuItemSetting.Text = "Export Schedulations";
                MenuItem mnuItemSetting2 = new MenuItem();
                mnuItemSetting2.Text = "Run Now";
                mnuContextMenu.MenuItems.Add(mnuItemSetting2);
                mnuContextMenu.MenuItems.Add(mnuItemSetting);             
                MenuItem mnuItemSettingRC = new MenuItem();
                mnuItemSettingRC.Text = "Send Config to Service";
                mnuItemSettingRC.Click += new EventHandler(btnRefreshC_Click);
                mnuItemSetting.Click += new EventHandler(btnExport_Click);
                mnuItemSetting2.Click += new EventHandler(Run_Now);
                mnuContextMenu.MenuItems.Add(mnuItemSettingRC);
            }
            else if (e.Button == MouseButtons.Right && listView1.Items.Count > 0)
            {
                //Create a Context Menu
                ContextMenu mnuContextMenu = new ContextMenu();
                this.listView1.ContextMenu = mnuContextMenu;
                MenuItem mnuItemSetting = new MenuItem();
                MenuItem mnuItemSettingRC = new MenuItem();
                mnuItemSettingRC.Text = "Send Config to Service";
                mnuItemSettingRC.Click += new EventHandler(btnRefreshC_Click);
                mnuItemSetting.Text = "Export Schedulations";
                mnuContextMenu.MenuItems.Add(mnuItemSetting);
                mnuContextMenu.MenuItems.Add(mnuItemSettingRC);
                mnuItemSetting.Click += new EventHandler(btnExport_Click);

            }
        }

        private void btnRefreshC_Click(object sender, EventArgs e)
        {
            //Try to Reload Settings in the AleScheduler_Service
            if (IsServiceInstalled("AleScheduler_Service"))
            {
                AleScheduler_ServiceController.ServiceName = "AleScheduler_Service";
                AleScheduler_ServiceController.DisplayName = "AleScheduler_Service";
                AleScheduler_ServiceController.MachineName = System.Environment.MachineName;
                AleScheduler_ServiceController.ExecuteCommand(129);
            }
        }

        private void TriggerICO_Click(object sender, EventArgs e)
        {
            #region Save_Schedule_Before_Add_Triggers
            if (this.txtScheduleName.Text.Trim() == string.Empty || this.txtFileToSchedule.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Insert Name of schedule and File to Schedule !", "AleScheduler", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else if (this.txtScheduleName.Text.Trim() == "MailConfig")
            {
                MessageBox.Show("Unable to Save Schedulations\nName of schedule reserved !\nChange Schedulations name", "AleScheduler", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            //Check if File to Schedule Exist
            if (!System.IO.File.Exists(this.txtFileToSchedule.Text.Trim()))
            {
                if (MessageBox.Show(this, "File To Schedule Not Found !\n" +
                    "Do You want to save anyway ?", "AleScheduler", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
                    return;
            }


            frmMailConfig.checkappkey();
            RegistryKey reg = Registry.LocalMachine.OpenSubKey("Software", true).OpenSubKey("AleScheduler", true);
            #region Set Schedulations Code
            int Code = 0;
            RegistryKey subKey;
            string[] subKeys = null;
            try
            { subKeys = reg.GetSubKeyNames(); }
            catch
            { Code = 1; }
            foreach (string strName in subKeys)
            {
                subKey = reg.OpenSubKey(strName);
                if ((subKey == null) || (strName == "MailConfig"))
                    continue;
                int regCode = (int)subKey.GetValue("Code");
                if (regCode > Code)
                    Code = regCode;
            }
            Code++;
            #endregion
            if (reg == null)
            {
                MessageBox.Show("Error unable to create the registry key 'AleScheduler'", "AleScheduler");
                return;
            }

            RegistryKey newKey = reg.CreateSubKey(txtScheduleName.Text.Trim());
            if (newKey == null)
            {
                MessageBox.Show("Error unable to create the registry key " + txtScheduleName.Text, "AleScheduler");
                return;
            }

            //Set Application Default Path
            if ((this.pathexe == null || this.pathexe == string.Empty) && this.txtFileToSchedule.Text != string.Empty)
                this.pathexe = System.IO.Path.GetDirectoryName(this.txtFileToSchedule.Text.Trim());
            //Write value of Key, before test the existance of value
            RegistryKey checkreg = Registry.LocalMachine.OpenSubKey("Software", true).OpenSubKey("AleScheduler", true).OpenSubKey(this.txtScheduleName.Text, true);
            if (Convert.ToInt32(checkreg.GetValue("Code", "0")) == 0)
            {
                newKey.SetValue("Code", Code);
            }
            newKey.SetValue("FileToRun", (string)txtFileToSchedule.Text.Trim());
            newKey.SetValue("ScheduleType", Convert.ToInt16(cmbSheduleType.SelectedIndex + 1));
            string hour = this.numericUpDown1.Value.ToString();
            string minutes = this.numericUpDown2.Value.ToString();
            if (hour.Length <= 1 && hour.StartsWith("0"))
            {
                hour = "00";
            }
            else if ((hour.Length == 1) && (!hour.StartsWith("0")))
            {
                hour = "0" + hour;
            }
            if (minutes.Length <= 1 && minutes.StartsWith("0"))
            {
                minutes = "00";
            }
            else if ((minutes.Length == 1) && (!minutes.StartsWith("0")))
                minutes = "0" + minutes;
            newKey.SetValue("Time", hour + ":" + minutes);
            if (this.cmbSheduleType.SelectedIndex == 5)
            {
                //if (this.cmbSheduleType.SelectedIndex == 5) is a Session Change Schedulation !
                newKey.SetValue("OnSessionChange", this.chkweek.SelectedIndex + 1);
                newKey.SetValue("Day", "All Day");
            }
            else if (this.cmbSheduleType.SelectedIndex == 2 || this.cmbSheduleType.SelectedIndex == 3)
            {
                newKey.SetValue("Day", this.dateTimePickerDay.Value.ToShortDateString());
            }
            else if (this.cmbSheduleType.SelectedIndex == 1)
            {
                newKey.SetValue("Day", DaysOfWeek[this.chkweek.SelectedIndex]);
            }
            else
            {
                newKey.SetValue("Day", "All Day");
            }
            newKey.SetValue("Every_Time", (int)this.numericUpDown3.Value);
            newKey.SetValue("SendMail", this.checkeMail.Checked);
            newKey.SetValue("Disabled", this.checkDisabled.Checked);
            newKey.SetValue("PathEXE", this.pathexe ?? string.Empty);
            newKey.SetValue("Arguments", this.txtExeArguments.Text.Trim());

            //Write Timeout value in milliseconds
            string valTimeOut = this.txtTimeOut.Text.Trim();
            int TimeOut = 0;
            if (valTimeOut.EndsWith("hou"))
            {
                TimeOut = Convert.ToInt32(valTimeOut.Remove(valTimeOut.Length - 3, 3));
                TimeOut = (TimeOut * 60) * 60; //Convert in Seconds
                TimeOut = TimeOut * 1000; //Convert to Milliseconds
                newKey.SetValue("Timeout", TimeOut);
            }
            else if (valTimeOut.EndsWith("min"))
            {
                TimeOut = Convert.ToInt32(valTimeOut.Remove(valTimeOut.Length - 3, 3));
                TimeOut = TimeOut * 60; //Convert in Seconds
                TimeOut = TimeOut * 1000; //Convert to Milliseconds
                newKey.SetValue("Timeout", TimeOut);
            }
            else if (valTimeOut != string.Empty)
            {
                TimeOut = Convert.ToInt32(valTimeOut);
                TimeOut = TimeOut * 1000; //Convert to Milliseconds
                newKey.SetValue("Timeout", TimeOut);
            }
            else
                newKey.SetValue("Timeout", TimeOut);

            //Update the listView
            UpdateListBox();
            #endregion
            frmTriggers fr = new frmTriggers();
            fr.schName = this.txtScheduleName.Text;
            fr.ShowDialog();
        }

        private void listView1_KeyUp(object sender, KeyEventArgs e)
        {
            ListView.SelectedListViewItemCollection lvItemCol = listView1.SelectedItems;
            if (this.listView1.Items.Count > 0 && this.listView1.SelectedItems.Count > 0 && e.KeyCode == Keys.Delete)
            {
                System.Collections.IEnumerator colEnum = lvItemCol.GetEnumerator();
                colEnum.MoveNext();
                ListViewItem lvItem = (ListViewItem)colEnum.Current;
                RegistryKey regKey = Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("AleScheduler", true);

                if (regKey == null)
                {
                    MessageBox.Show(this, "Unable to open the registry key", "AleScheduler");
                    return;
                }

                regKey.DeleteSubKeyTree(lvItem.Text);
                UpdateListBox();
                this.txtScheduleName.Text = string.Empty;
                this.txtFileToSchedule.Text = string.Empty;
                this.txtExeArguments.Text = string.Empty;
                this.cmbSheduleType.SelectedIndex = -1;
            }
            listboxsel();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            #region Save_Schedule_Before_Add_Triggers
            if (this.txtScheduleName.Text.Trim() == string.Empty || this.txtFileToSchedule.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Insert Name of schedule and File to Schedule !", "AleScheduler", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else if (this.txtScheduleName.Text.Trim() == "MailConfig")
            {
                MessageBox.Show("Unable to Save Schedulations\nName of schedule reserved !\nChange Schedulations name", "AleScheduler", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            //Check if File to Schedule Exist
            if (!System.IO.File.Exists(this.txtFileToSchedule.Text.Trim()))
            {
                if (MessageBox.Show(this, "File To Schedule Not Found !\n" +
                    "Do You want to save anyway ?", "AleScheduler", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
                    return;
            }


            frmMailConfig.checkappkey();
            RegistryKey reg = Registry.LocalMachine.OpenSubKey("Software", true).OpenSubKey("AleScheduler", true);
            #region Set Schedulations Code
            int Code = 0;
            RegistryKey subKey;
            string[] subKeys = null;
            try
            { subKeys = reg.GetSubKeyNames(); }
            catch
            { Code = 1; }
            foreach (string strName in subKeys)
            {
                subKey = reg.OpenSubKey(strName);
                if ((subKey == null) || (strName == "MailConfig"))
                    continue;
                int regCode = (int)subKey.GetValue("Code");
                if (regCode > Code)
                    Code = regCode;
            }
            Code++;
            #endregion
            if (reg == null)
            {
                MessageBox.Show("Error unable to create the registry key 'AleScheduler'", "AleScheduler");
                return;
            }

            RegistryKey newKey = reg.CreateSubKey(txtScheduleName.Text.Trim());
            if (newKey == null)
            {
                MessageBox.Show("Error unable to create the registry key " + txtScheduleName.Text, "AleScheduler");
                return;
            }

            //Set Application Default Path
            if ((this.pathexe == null || this.pathexe == string.Empty) && this.txtFileToSchedule.Text != string.Empty)
                this.pathexe = System.IO.Path.GetDirectoryName(this.txtFileToSchedule.Text.Trim());
            //Write value of Key, before test the existance of value
            RegistryKey checkreg = Registry.LocalMachine.OpenSubKey("Software", true).OpenSubKey("AleScheduler", true).OpenSubKey(this.txtScheduleName.Text, true);
            if (Convert.ToInt32(checkreg.GetValue("Code", "0")) == 0)
            {
                newKey.SetValue("Code", Code);
            }
            newKey.SetValue("FileToRun", (string)txtFileToSchedule.Text.Trim());
            newKey.SetValue("ScheduleType", Convert.ToInt16(cmbSheduleType.SelectedIndex + 1));
            string hour = this.numericUpDown1.Value.ToString();
            string minutes = this.numericUpDown2.Value.ToString();
            if (hour.Length <= 1 && hour.StartsWith("0"))
            {
                hour = "00";
            }
            else if ((hour.Length == 1) && (!hour.StartsWith("0")))
            {
                hour = "0" + hour;
            }
            if (minutes.Length <= 1 && minutes.StartsWith("0"))
            {
                minutes = "00";
            }
            else if ((minutes.Length == 1) && (!minutes.StartsWith("0")))
                minutes = "0" + minutes;
            newKey.SetValue("Time", hour + ":" + minutes);
            if (this.cmbSheduleType.SelectedIndex == 2 || this.cmbSheduleType.SelectedIndex == 3)
            {
                newKey.SetValue("Day", this.dateTimePickerDay.Value.ToShortDateString());
            }
            else if (this.cmbSheduleType.SelectedIndex == 1)
            {
                newKey.SetValue("Day", DaysOfWeek[this.chkweek.SelectedIndex]);
            }
            else
            {
                newKey.SetValue("Day", "All Day");
            }
            newKey.SetValue("Every_Time", (int)this.numericUpDown3.Value);
            newKey.SetValue("SendMail", this.checkeMail.Checked);
            newKey.SetValue("Disabled", this.checkDisabled.Checked);
            newKey.SetValue("PathEXE", this.pathexe ?? string.Empty);
            newKey.SetValue("Arguments", this.txtExeArguments.Text.Trim());

            //Write Timeout value in milliseconds
            string valTimeOut = this.txtTimeOut.Text.Trim();
            int TimeOut = 0;
            if (valTimeOut.EndsWith("hou"))
            {
                TimeOut = Convert.ToInt32(valTimeOut.Remove(valTimeOut.Length - 3, 3));
                TimeOut = (TimeOut * 60) * 60; //Convert in Seconds
                TimeOut = TimeOut * 1000; //Convert to Milliseconds
                newKey.SetValue("Timeout", TimeOut);
            }
            else if (valTimeOut.EndsWith("min"))
            {
                TimeOut = Convert.ToInt32(valTimeOut.Remove(valTimeOut.Length - 3, 3));
                TimeOut = TimeOut * 60; //Convert in Seconds
                TimeOut = TimeOut * 1000; //Convert to Milliseconds
                newKey.SetValue("Timeout", TimeOut);
            }
            else if (valTimeOut != string.Empty)
            {
                TimeOut = Convert.ToInt32(valTimeOut);
                TimeOut = TimeOut * 1000; //Convert to Milliseconds
                newKey.SetValue("Timeout", TimeOut);
            }
            else
                newKey.SetValue("Timeout", TimeOut);

            //Update the listView
            UpdateListBox();
            #endregion
            FormHappyHour frb = new FormHappyHour();
            frb.schName = this.txtScheduleName.Text;
            frb.ShowDialog();
        }

        private void mailSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Show an InputBox for eMail address
            frmMailConfig mail = new frmMailConfig();
            mail.ShowDialog();
            if (mail != null)
            {
                mail.Close();
                mail.Dispose();
            }
        }


        private void btnEditTriggers_Click(object sender, EventArgs e)
        {
            TriggerICO_Click(sender,e);
        }

        private void newTaskToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.txtScheduleName.Text = "New Task";
        }

        private void chkLogFile_CheckedChanged(object sender, EventArgs e)
        {
            this.txtLogPath.Enabled = this.chkLogFile.Checked;
            if (this.chkLogFile.Checked)
                this.txtLogPath.Text = "%LOGDIR%";
        }

        private void txtLogPath_DoubleClick(object sender, EventArgs e)
        {
            FolderBrowserDialog opfile = new FolderBrowserDialog();
            opfile.Description = "AleScheduler - Select Log Directory";
            opfile.ShowNewFolderButton = true;
            if (opfile.ShowDialog() == DialogResult.OK)
                this.txtFileToSchedule.Text = opfile.SelectedPath;
        }

        private void chkInteractDesktop_CheckedChanged(object sender, EventArgs e)
        {
            this.txtTimeOut.Enabled = !this.chkInteractDesktop.Checked;
            this.lblTimeOut.Enabled = !this.chkInteractDesktop.Checked;
        }

        private void timerStatus_Tick(object sender, EventArgs e)
        {
            //This timer Check if the Service Status periodically
            Service_Control();
        }

    }
}

